<?php

namespace App\Http\Controllers\Admin;

use App\Admin;
use App\Http\Requests\StoreAdmin;
use App\Http\Requests\UpdateAdmin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $admins = Admin::latest('updated_at')->paginate(30);
        return view('admin.admin.index', compact('admins'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.admin.create');
    }

    /**
     * @param \App\Http\Requests\StoreAdmin $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(StoreAdmin $request)
    {
        $data = $request->all();
        if ($request->has('password')) {
            $data['password'] = bcrypt($request->input('password'));
        }

        if (Admin::create($data)) {
            return redirect(route('admin.index'))->with('success', '添加成功');
        } else {
            return redirect()->back()->with('error', '注册失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Admin $admin
     * @return \Illuminate\Http\Response
     */
    public function show(Admin $admin)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Admin $admin
     * @return \Illuminate\Http\Response
     */
    public function edit(Admin $admin)
    {
        return view('admin.admin.edit', compact('admin'));
    }

    /**
     * @param \App\Http\Requests\UpdateAdmin $request
     * @param \App\Admin                     $admin
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(UpdateAdmin $request, Admin $admin)
    {
        $data = array_filter($request->all());

        if ($request->has('password')) {
            $data['password'] = bcrypt($request->input('password'));
        }

        if ($admin->update($data)) {
            return redirect(route('admin.index'))->with('success', '更新成功');
        } else {
            return redirect()->back()->with('error', '更新失败');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Admin $admin
     * @return \Illuminate\Http\Response
     */
    public function destroy(Admin $admin)
    {
        $this->authorize('delete', $admin);

        if ($admin->delete()) {
            return redirect(route('admin.index'))->with('success', '删除成功');
        } else {
            return redirect()->back()->with('error', '删除失败');
        }
    }
}
